package com.example.springai.langchat;


import dev.langchain4j.community.store.embedding.redis.RedisEmbeddingStore;
import dev.langchain4j.data.document.Metadata;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;

import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.model.openai.OpenAiEmbeddingModel;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.rag.content.Content;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.rag.query.Query;
import dev.langchain4j.store.embedding.EmbeddingMatch;
import dev.langchain4j.store.embedding.EmbeddingSearchRequest;
import dev.langchain4j.store.embedding.EmbeddingSearchResult;
import dev.langchain4j.store.embedding.EmbeddingStore;

import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import redis.clients.jedis.Jedis;

import java.io.FileWriter;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import static dev.langchain4j.store.embedding.filter.MetadataFilterBuilder.metadataKey;


public class RedisEmbeddingStoreExample {

    public static void main(String[] args) {

//
//        Jedis jedis = new Jedis("127.0.0.1", 6379);
//        jedis.flushDB();  // 清空当前数据库

//        EmbeddingStore<TextSegment> embeddingStore = RedisEmbeddingStore.builder()
//                .host("127.0.0.1")
//                .port(6379)
////                .metadataConfig()
//                .dimension(1024)
//                .build();
                InMemoryEmbeddingStore<TextSegment> embeddingStore = new InMemoryEmbeddingStore<>();

        EmbeddingModel embeddingModel = OpenAiEmbeddingModel.builder()
                .baseUrl("https://api.siliconflow.cn/v1")
//                .proxy(new Proxy(Proxy.Type.HTTP,new InetSocketAddress("127.0.0.1", 7890)))
                .apiKey("sk-nrvjihoykgbjabnelziszukgkcankraqcwtvohvpcuepuyyz").modelName("Pro/BAAI/bge-m3").logRequests(true).logResponses(true).dimensions(1024)
                .build();

        TextSegment segment1 = TextSegment.from("今天买了一双鞋子", new Metadata().put("time","2025年4月").put("姓名","张昊")
                .put("鞋子","nike").put("userId",12345));
        TextSegment segment3 = TextSegment.from("今天买了一双白色鞋子", new Metadata().put("time","2025年4月").put("姓名","张昊")
                .put("鞋子","nike").put("userId",123456));

        Embedding embedding1 = embeddingModel.embed(segment1).content();
        String add = embeddingStore.add(embedding1, segment1);

        Embedding embedding3 = embeddingModel.embed(segment3).content();
        embeddingStore.add(embedding3,segment3);
        TextSegment segment2 = TextSegment.from("The weather is good today.");
        Embedding embedding2 = embeddingModel.embed(segment2).content();
        embeddingStore.add(embedding2, segment2);

        Embedding queryEmbedding = embeddingModel.embed("鞋子").content();
        EmbeddingSearchRequest embeddingSearchRequest = EmbeddingSearchRequest.builder()
                .queryEmbedding(queryEmbedding)

                .filter(metadataKey("userId").isEqualTo(12345))
                .maxResults(1)
                .build();

        EmbeddingSearchResult<TextSegment> relevant = embeddingStore.search(embeddingSearchRequest);
//        List<EmbeddingMatch<TextSegment>> relevant = embeddingStore.findRelevant(queryEmbedding, 1);

        System.out.println("relevant = " + relevant.matches());
//        EmbeddingMatch<TextSegment> embeddingMatch = relevant.matches().get(0);
//        Metadata metadata = embeddingMatch.embedded().metadata();
//        System.out.println("metadata = " + metadata);
//        System.out.println(embeddingMatch.score()); // 0.8144288659095
//        System.out.println(embeddingMatch.embedded().text()); // I like football.

//        redis.stop();


//        String serializedStore = embeddingStore.serializeToJson();
//        System.out.println("serializedStore = " + serializedStore);
//        String directoryPath = "D:\\data";
//        String filePath_new  = directoryPath + "\\embedding_store.json";
//
//        try {
//            // 创建目录（如果不存在）
//            Path dirPath = Paths.get(directoryPath);
//            if (!Files.exists(dirPath)) {
//                Files.createDirectories(dirPath); // 会创建所有不存在的父目录
//                System.out.println("目录已创建: " + directoryPath);
//            }
//
//            // 写入文件
//            FileWriter fileWriter = new FileWriter(filePath_new);
//            fileWriter.write(serializedStore);
//            fileWriter.close();
//            System.out.println("serializedStore 已成功保存到: " + filePath_new);
//        } catch (IOException e) {
//            System.err.println("写入文件时发生错误: " + e.getMessage());
//            e.printStackTrace();
//        }
        String filePath = "D:\\data\\embedding_store.json";
        embeddingStore.serializeToFile(filePath);
//        System.out.println("embeddingStoreLocat.serializeToJson() = " + embeddingStore.serializeToJson());
//        InMemoryEmbeddingStore<TextSegment> embeddingStore1 = InMemoryEmbeddingStore.fromFile(filePath);
//        String s = embeddingStore1.serializeToJson();
//        System.out.println(s);
        // --- 文件保存结束 ---
    }
}